#!/usr/bin/env python

import os
import wx
import app
import json
import model
import dialog
import shutil
import component

class Main(component.Presenter):
    '''Main class
    
    @author Julot <andy.julot@gmail.com>
    @since Saturday, January 14, 2012. 09:07 AM'''
    
    _folder = ''
    _image = ''
    
    def __init__(self, view, interactor):
        super(Main, self).__init__(view, interactor)
        self.readVerSashPos()
        self.readHorSashPos()
        self.readFolder()
        self.populateFiles(self._folder)
        
    def onClose(self):
        self.writeVerSashPos()
        self.writeHorSashPos()
        self.writeFolder()
        super(Main, self).onClose()
    
    def close(self):
        self.view.Close()
    
    def readVerSashPos(self):
        pos = app.Config().ReadInt('%s/VerSash' % self.view.Name, -1)
        if pos != -1: self.view.vSplitter.SashPosition = pos
    
    def readHorSashPos(self):
        pos = app.Config().ReadInt('%s/HorSash' % self.view.Name, -1)
        if pos != -1: self.view.hSplitter.SashPosition = pos
    
    def readFolder(self):
        self._folder = app.Config().Read('%s/Folder' % self.view.Name, '')
    
    def writeVerSashPos(self):
        key = '%s/VerSash' % self.view.Name
        app.Config().WriteInt(key, self.view.vSplitter.SashPosition)
    
    def writeHorSashPos(self):
        key = '%s/HorSash' % self.view.Name
        app.Config().WriteInt(key, self.view.hSplitter.SashPosition)
    
    def writeFolder(self):
        key = '%s/Folder' % self.view.Name
        app.Config().Write(key, self._folder)
    
    _about = None
    
    def showAbout(self):
        if not self._about: self._about = dialog.About(self.view)
        self._about.Center()
        self._about.Show()

    def browse(self):
        folder = self.view.dirDialog(defaultPath=self._folder,
                                     style=wx.DD_DIR_MUST_EXIST)
        if folder: self.populateFiles(folder)
    
    def populateFiles(self, folder):
        if not os.path.lexists(folder): return
        
        self._folder = folder
        exts = ('png', 'jpg', 'jpeg', 'gif', 'tif')
        filenames = os.listdir(folder)
        files = []
        for filename in filenames:
            name, ext = os.path.splitext(filename)
            ext = ext.lower()[1:]
            if ext in exts:
                files.append(filename)
        self.view.files.values = files
    
    def update(self):
        images = self.view.files.selection
        if not images:
            message = 'Please select at least one image.'
            self.view.messageDialog(message, 'Error')
            return
        
        code = self.view.form.code.Value
        if not code:
            message = 'No cannot be blank'
            self.view.messageDialog(message, 'Error')
            return
        
        synopsis = self.view.form.synopsis.Value
        if not synopsis:
            message = 'Synopsis cannot be blank'
            self.view.messageDialog(message, 'Error')
            return
        
        self.view.busyCursor()
        self.view.form.disable()
        doc = model.Document()
        doc.code = code
        doc.extension = 'pdf'
        doc.synopsis = synopsis
        doc.images = images
        response = doc.upload(self._folder)
        ok = False
        if response:
            responses = json.loads(response)
            if responses['success']:
                id = responses['data']['id'][0]
                doc.id = id
                db = wx.GetApp().db
                db.add(doc)
                db.commit()
                doc.download('pdf')
                path = os.path.join(self._folder, self._image)
                newPath = os.path.join('document', 'original',
                                       '%s.%s' % (id, self._image))
                shutil.copyfile(path, newPath)
                #shutil.os.rename(path, newPath)
                
                self.populateFiles(self._folder)
                self.view.image.clear()
                self.view.form.code.Value = ''
                self.view.form.synopsis.Value = ''
                
                ok = True
        if not ok:
            s = 'Update failed.\n' + \
              'Please try again later or contact your administrator.'
            self.view.messageDialog(s, 'Update')
        self.view.form.enable()
        self.view.idle()
        
    def show(self, filename):
        self._image = filename
        path = os.path.join(self._folder, filename)
        try:
            image = wx.Image(path, wx.BITMAP_TYPE_ANY)
        except:
            self.view.messageDialog('Invalid image', 'Error', wx.OK)
        else:
            self.view.busyCursor()
            self.view.image.value = image
            self.view.idle()
        
    def startFile(self):
        if not (self._folder and self._image): return
        
        path = os.path.join(self._folder, self._image)
        if os.path.exists(path):
            os.startfile(path)